"""
均匀分布划分数据集
"""
import os

import matplotlib.pyplot as plt
import numpy as np
import xlrd

BASE_PATH = './XlxsFiles'
XLSX_PATH = os.path.join(BASE_PATH, 'sharp_scoring_3840.xlsx')


def readXlrd(excelFile):
    scoreDict = {}

    data = xlrd.open_workbook(excelFile)

    # sheet1
    table = data.sheet_by_index(0)

    for rowNum in range(table.nrows):
        if rowNum == 0:
            continue

        rowVale = table.row_values(rowNum)

        # 检查编号
        checkNum = 'DX' + str(int(rowVale[2]))

        # 评分 1
        score1 = rowVale[15]

        # 评分 2
        score2 = rowVale[16]

        # 平均评分
        score = float(rowVale[17])
        if score != (score1 + score2) * 0.5:
            print(rowNum)
            break

        scoreDict[checkNum] = score
    # for

    return scoreDict


def evenlyDivided(scoreDict, categorieNum):
    scoreList = []
    for k, v in scoreDict.items():
        scoreList.append(v)
    scoreList = np.array(scoreList).reshape(1, -1)

    # 生成直方图数据
    hist, bin_edges = np.histogram(scoreList, 1000)

    # 调试
    tmp = hist / sum(hist)
    # 求 cdf
    cdf = np.cumsum(hist / sum(hist))

    plt.figure(figsize=(16, 5))
    plt.plot(bin_edges[1:], cdf, color='#000000')
    plt.xlim([scoreList.min(), scoreList.max()])
    plt.ylim([0, 1])
    plt.grid()
    plt.show()

    histCols = hist.shape[0]
    totalNum = scoreList.shape[1]
    count = 0
    scaleList = []
    for i in range(histCols):
        count = count + hist[i]
        if (count >= totalNum / categorieNum) or (i == (histCols - 1)):
            # 真实标度应该为 标度 * 组距
            scaleList.append(i / histCols * scoreList.max())
            count = 0

    dividedDict = {}

    lenOfScaleList = len(scaleList)
    maxIndexOfScaleList = lenOfScaleList - 1
    for checkNum, score in scoreDict.items():
        for i in range(maxIndexOfScaleList + 1):
            if i == 0:
                if score <= scaleList[0]:
                    dividedDict[checkNum] = i + 1
            elif scaleList[i - 1] <= score <= scaleList[i]:
                tmp1 = scaleList[i - 1]
                tmp2 = scaleList[i]
                dividedDict[checkNum] = i + 1
    # for
    return dividedDict


if __name__ == '__main__':
    scoreDict = readXlrd(XLSX_PATH)

    scoreList = []
    for k, v in scoreDict.items():
        scoreList.append(v)

    # 画直方图
    plt.figure(figsize=(16, 5))
    plt.hist(scoreList, bins=200)
    plt.show()

    evenlyDivided(scoreDict, categorieNum=7)
